package cn.bonoon.kernel.security;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.batatasframework.util.RunningStatistics;

public class LogonUserRuntimeCollection extends ArrayList<LogonUserRuntime>{

	private static final long serialVersionUID = -6084956068834056888L;

	private final int total;
	
	private String message;
	
	/** 当前的sessionid，因为本人是不允允许强制本人退出的 */
	private final String sid;
	
	/** 指定那些用户不能强制退出的 */
	private List<String> excludes = Collections.emptyList();
	
	private final RunningStatistics statistics;

	public LogonUserRuntimeCollection(HttpServletRequest request, RunningStatistics statistics, int total, int size){
		super(size);
		this.sid = request.getSession().getId();
		this.statistics = statistics;
		this.total = total;
	}
	
	public boolean outable(String sid, String lname){
		if(this.sid.equals(sid)) return false;
		for(String ex : excludes){
			if(lname.startsWith(ex)) return false;
		}
		
		return true;
	}
	
	public String getTotal() {
		return size() + "/" + total;
	}
	
	private boolean asc;
	private int sort;
	
	public void sort(int sort, String order){
		if(sort >= 0){
			this.sort = sort;
			this.asc = "asc".equals(order);
			Collections.sort(this, comparator);
		}
	}
	
	private int internalCompare(String o1, String o2){
		return asc ? o1.compareTo(o2) : o2.compareTo(o1);
	}

	private int internalCompare(long o1, long o2){
		return asc ? Long.compare(o1, o2) : Long.compare(o2, o1);
	}
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public RunningStatistics getStatistics() {
		return statistics;
	}

	private final Comparator<LogonUserRuntime> comparator = new Comparator<LogonUserRuntime>(){

		@Override
		public int compare(LogonUserRuntime o1, LogonUserRuntime o2) {
			switch (sort) {
			case 0: return internalCompare(o1.getUsername(), o2.getUsername());
			case 1: return internalCompare(o1.getLoginAt(), o2.getLoginAt());
			case 2: return internalCompare(o1.getIp(), o2.getIp());

			case 3: return internalCompare(o1.getStatistics().getTotal(), o2.getStatistics().getTotal());
			case 4: return internalCompare(o1.getStatistics().getMax(),   o2.getStatistics().getMax());
			case 5: return internalCompare(o1.getStatistics().getArg(),   o2.getStatistics().getArg());
			case 6: return internalCompare(o1.getStatistics().getMin(),   o2.getStatistics().getMin());
			}
			return 0;
		}

	};
}
